<template>
	<view class="proinfo" style="background-color: #fff;height: 500px;">
		<image :src="product_info.imageURL" class="top" style="height: 250px;"></image>
		<!-- 商品价格 -->
		<view class="proinfo-cont">
			<view class="price">￥{{product_info.price}}</view>
			<!-- 信息主体区域 -->
			<view class="goods-info-body">
				<!-- 商品名称 -->
				<view class="goods-name">{{product_info.description}}</view>
				<!-- 收藏 -->
				<view class="favi" @click="toggleFavorite">
					<uni-icons :type="isFavorite ? 'heart-filled' : 'heart'" size="18"
						:color="isFavorite ? 'red' : 'gray'"></uni-icons>
					<text>{{isFavorite ? '已收藏' : '收藏'}}</text>
				</view>
			</view>
			<!-- 运费 -->
			<view class="yf">快递：免运费</view>
		</view>
		<uni-section>
			<uni-goods-nav :fill="true" :options="options" :button-group="customButtonGroup" @click="onClick"
				@buttonClick="buttonClick" />
		</uni-section>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	
	export default {
		computed: {
			...mapState('m_user', ['userId']),
		},
		data() {
			return {
				// 商品详情对象
				product_info: {},
				options: [{
						icon: 'home',
						text: '首页'
					},
					{
						icon: 'heart',
						text: '收藏夹',
						infoColor: "#f5f5f5"
					},
					{
						icon: 'cart',
						text: '购物车',
						info: 2
					},
				],
				buttonGroup: [],
				customButtonGroup: [{
						text: '加入购物车',
						backgroundColor: 'linear-gradient(90deg, #1E83FF, #0053B8)',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: 'linear-gradient(90deg, #60F3FF, #088FEB)',
						color: '#fff'
					}
				],
				isFavorite: false // 添加收藏状态变量
			}
		},
		onLoad(options) {
			// 获取商品 Id
			const productId = options.productId
			// 调用请求商品详情数据的方法
			this.getGoodsDetail(productId)
			// 可以在这里调用API检查当前商品是否已被收藏，并设置isFavorite的值
			this.checkFavorite(this.userId, productId)
		},
		methods: {
			// 定义请求商品详情数据的方法
			async getGoodsDetail(productId) {
				try {
					const res = await uni.$http.get(`/productList/${productId}`)
					console.log(res.data.data)
					this.product_info = res.data.data
				} catch (error) {
					console.error(error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			 async toggleFavorite() {
			        try {
			            this.isFavorite = !this.isFavorite;
			            const res = await uni.$http.post(`/wx/favorite/${this.userId}/${this.product_info.productId}`, {
			                isFavorite: this.isFavorite
			            });
						
						console.log('点击收藏按钮结果:',res.data.msg)
			            if (!res.data.code) {
			                throw new Error(res.message || '操作失败');
			            }
			            uni.showToast({
			                title: this.isFavorite ? '收藏成功' : '取消收藏成功',
			                icon: 'success'
			            });
			        } catch (error) {
			            console.error(error);
			            this.isFavorite = !this.isFavorite; // 回滚
			            uni.showToast({
			                title: '请先登录',
			                icon: 'none'
			            });
			        }
			    },
			onClick(e) {
				if(e.content.text=='收藏夹'){
					wx.redirectTo({ url: '/subpkg/favorite/favorite' });
				}
				if(e.content.text=='首页'){
					wx.switchTab({ url: '/pages/home/home' });
				}
				if(e.content.text=='购物车'){
					wx.switchTab({ url: '/pages/cart/cart' });
				}
			},
			buttonClick(e) {
				console.log(e)
				this.options[2].info++
			},
			 async checkFavorite(userId, productId) {
			        try {
			            const res = await uni.$http.get(`/wx/favorite/check/${userId}/${productId}`)
						console.log(res.data)
						console.log('检查商品是否已被收藏:',res.data.data.isFavorite)
			            this.isFavorite = res.data.data.isFavorite
			        } catch (error) {
			            console.error(error)
			        }
			    },
		},
	}
</script>

<style lang="scss">
	// 商品信息区域的样式
	.proinfo {
		display: flex;
		flex-direction: column;
		justify-content: space-between; // 顶部和底部内容之间分配空间
		height: 100vh; // 使用视口高度确保内容填满整个屏幕
		box-sizing: border-box; // 确保padding不会增加元素的总高度

		.proinfo-cont {
			padding: 10px;
			padding-right: 0;
			flex: 1; // 占据剩余空间（除了底部固定区域）

			.price {
				color: #c00000;
				font-size: 24px;
				margin: 10px 0;
			}

			.goods-info-body {
				display: flex;
				justify-content: space-between;

				.goods-name {
					font-size: 13px;
					padding-right: 10px;
				}

				// 收藏区域
				.favi {
					width: 120px;
					font-size: 12px;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					border-left: 1px solid #efefef;
					color: gray;
				}
			}

			// 运费
			.yf {
				margin: 10px 0;
				font-size: 12px;
				color: gray;
			}
		}

		// 确保 uni-section 固定在底部
		uni-section {
			margin-top: auto; // 使用自动外边距将元素推到容器底部
		}
	}
</style>